/*
Created by Borui Wang (bwang29@wisc.edu)
March, 2012, GoCuro
ws.js
*/

var host = "http://gocuro2.herokuapp.com/";
//var host = "http://localhost:3000/";

var items_ui = [];

function singe_item(item_id,employee_name,user_id,jobsite_name,jobsite_id,name,barcode_id,quantity,device_id,updated_at,html_data)
{
	this.item_id=item_id;
	this.employee_name=employee_name;
	this.user_id=user_id;
	this.jobsite_name=jobsite_name;
	this.jobsite_id=jobsite_id;
	this.name=name;
	this.barcode_id=barcode_id;
	this.quantity=quantity;
	this.device_id=device_id;
	this.updated_at=updated_at;	
	this.html_data=html_data;	
}


/* logout */
function logOut(){
	persist_clear();
	
}


/*get company*/
function　getCompaniesGet(){
	$('#newuser_jobsite_choices').html("");
	var targetUrl = host+"companies/get_companies"
	WS.makeGenericGetRequest(targetUrl, getCompaniesGetHandle,"","");
	
}
function getCompaniesGetHandle(responseText, statusText){
	var responseJSON = responseText;
		if(typeof responseJSON.error !== "undefined"){
		$('#newuser_errbox').html("Error: "+responseJSON.error);
		$('#newuser_wait').fadeOut();
		$('#newuser_errbox').fadeIn();
	}else{
		var responseJSON = responseText;
		var HTMLcontent='<select class="span3" id="newuser_company_select" onChange="getJobsitesGet(this.value);">';		
		HTMLcontent += 	"<option value=\"\">" + "Select company" + "</option>"
		for(var index = 0; index < responseJSON.length; index ++ )
		{
			HTMLcontent += "<option value=\""+responseJSON[index].id+"\">" + responseJSON[index].name + "</option>"
		}
		HTMLcontent+="</select>";
		
		$('#newuser_company_choices').html(HTMLcontent);
		$('#newuser_enable_select_company_jobsite').fadeIn();
		$('#newuser_wait').fadeOut();
	}
}


/*edit company*/
function　editCompaniesGet(){
	$('#edituser_jobsite_choices').html("");
	var targetUrl = host+"companies/get_companies"
	WS.makeGenericGetRequest(targetUrl, editCompaniesGetHandle,"","");
	
}
function editCompaniesGetHandle(responseText, statusText){
	var responseJSON = responseText;
		if(typeof responseJSON.error !== "undefined"){
		$('#edituser_errbox').html("Error: "+responseJSON.error);
		$('#edituser_wait').fadeOut();
		$('#edituser_errbox').fadeIn();
	}else{
		var responseJSON = responseText;
		var HTMLcontent='<select class="span3" id="edituser_company_select" onChange="editJobsitesGet(this.value);">';		
		HTMLcontent += 	"<option value=\"\">" + "Select company" + "</option>"
		for(var index = 0; index < responseJSON.length; index ++ )
		{
			HTMLcontent += "<option value=\""+responseJSON[index].id+"\">" + responseJSON[index].name + "</option>"
		}
		HTMLcontent+="</select>";
		
		$('#edituser_company_choices').html(HTMLcontent);
		$('#edituser_enable_select_company_jobsite').fadeIn();
		$('#edituser_wait').fadeOut();
		
		// find company nad jobsite using user data
		$("#edituser_company_select").val(edit_company_id);
		editJobsitesGet(edit_company_id);
	}
}



/*get jobsite*/
function　getJobsitesGet(company_index){
	$('#newuser_wait').fadeIn();
	var targetUrl = host+"jobsites/get_sites?company="+company_index;
	WS.makeGenericGetRequest(targetUrl, getJobsitesGetHandle,"","");
}
function getJobsitesGetHandle(responseText, statusText){
	var responseJSON = responseText;
		if(typeof responseJSON.error !== "undefined"){
		$('#newuser_errbox').html("Error: "+responseJSON.error);
		$('#newuser_wait').fadeOut();
		$('#newuser_errbox').fadeIn();
	}else{
		var HTMLcontent='<select class="span3" id="newuser_jobsite_select">';
								
		for(var index = 0; index < responseJSON.length; index ++ )
		{
			HTMLcontent += "<option value=\""+responseJSON[index].id+"\">" + responseJSON[index].name + "</option>"
		}
		HTMLcontent+="</select>";
		
		$('#newuser_jobsite_choices').html(HTMLcontent);
		$('#newuser_wait').fadeOut();
	}
}


/*get jobsite*/
function　editJobsitesGet(company_index){
	$('#edituser_wait').fadeIn();
	var targetUrl = host+"jobsites/get_sites?company="+company_index;
	WS.makeGenericGetRequest(targetUrl, editJobsitesGetHandle,"","");
}
function editJobsitesGetHandle(responseText, statusText){
	var responseJSON = responseText;
		if(typeof responseJSON.error !== "undefined"){
		$('#edituser_errbox').html("Error: "+responseJSON.error);
		$('#edituser_wait').fadeOut();
		$('#edituser_errbox').fadeIn();
	}else{
		var HTMLcontent='<select class="span3" id="edituser_jobsite_select">';
								
		for(var index = 0; index < responseJSON.length; index ++ )
		{
			HTMLcontent += "<option value=\""+responseJSON[index].id+"\">" + responseJSON[index].name + "</option>"
		}
		HTMLcontent+="</select>";
		
		$('#edituser_jobsite_choices').html(HTMLcontent);
		$('#edituser_wait').fadeOut();
		
				// find company nad jobsite using user data
		$("#edituser_jobsite_select").val(edit_site_id);
	}
}


/*create user*/
function　createUserPost(){
	$('#newuser_errbox').fadeOut();
	$('#newuser_wait').fadeIn();
	var targetUrl = host+"users";
	var postInstance = [];
	postInstance.username = escape($('#newuser_name').val());
	postInstance.pwd = escape($('#newuser_password').val());
	postInstance.email = escape($('#newuser_email').val());
	postInstance.site = escape($('#newuser_jobsite_select').val());
	postInstance.company = escape($('#newuser_company_select').val());
	postInstance.phone_number = escape($('#newuser_phonenumber').val());
	WS.makeGenericPOSTRequest(targetUrl, WS.toParam(postInstance), createUserPostHandle,"","");
}
function createUserPostHandle(responseText, statusText){
	var responseJSON = responseText;
	if(typeof responseJSON.error !== "undefined"){
		$('#newuser_errbox').html("Error: "+responseJSON.error);
		$('#newuser_wait').fadeOut();
		$('#newuser_errbox').fadeIn();
	}else{
		
		$('#newuser_wait').fadeOut();
		$('#newUser').modal('hide');
		$('#newuser_create_success_msgbox').fadeIn();
	}
}



/*edit user*/
function　editUserPost(){
	session_c = persist_read();
	if(session_c.gocuro_username!== "" && session_c.gocuro_username!== "undefined" && session_c.gocuro_username!== "Invalid"){
	
		$('#edituser_errbox').fadeOut();
		$('#edituser_wait').fadeIn();
		var targetUrl = host+"users/update/"+session_c.gocuro_user_id;
		var postInstance = [];
		postInstance.new_username = escape($('#edituser_name').val());
		postInstance.email = escape($('#edituser_email').val());
		postInstance.site = escape($('#edituser_jobsite_select').val());
		postInstance.company = escape($('#edituser_company_select').val());
		postInstance.phone_number = escape($('#edituser_phone_number').val());
		postInstance.device_id = session_c.gocuro_device_id
		postInstance.username = session_c.gocuro_username;
		postInstance.pwd = session_c.gocuro_password;
		WS.makeGenericPOSTRequest(targetUrl, WS.toParam(postInstance), editUserPostHandle,"","");
	}else{
		window.location.reload();
	}
}
function editUserPostHandle(responseText, statusText){
	var responseJSON = responseText;
	if(typeof responseJSON.error !== "undefined"){
		$('#edituser_errbox').html("Error: "+responseJSON.error);
		$('#edituser_wait').fadeOut();
		$('#edituser_errbox').fadeIn();
	}else{
		persist_write(escape($('#login_password').val()),responseJSON.username,responseJSON.userid,responseJSON.jobsiteid,responseJSON.jobsitename,responseJSON.deviceid)
		$('#login_status').html("Welcome, "+responseJSON.username+" @ "+ responseJSON.jobsitename +"  <a href='' onClick='logOut()'> Logout</a>")
		$('#edituser_wait').fadeOut();
		$('#editUser').modal('hide');
		$('#edituser_create_success_msgbox').html("Successdully updated user");
		$('#edituser_create_success_msgbox').fadeIn();
	}
}


/*get user*/
function　getUserPost(){
	session_c = persist_read();
	if(session_c.gocuro_username!== "" && session_c.gocuro_username!== "undefined" && session_c.gocuro_username!== "Invalid"){
		$('#edituser_errbox').fadeOut();
		$('#edituser_wait').fadeIn();
		var targetUrl = host+"users/"+session_c.gocuro_user_id;
		var postInstance = [];
		postInstance.username = session_c.gocuro_username;
		postInstance.pwd = session_c.gocuro_password;
		WS.makeGenericPOSTRequest(targetUrl, WS.toParam(postInstance), getUserPostHandle,"","");
	}else{
		window.location.reload();
	}
}
var edit_company_id = 1;
var edit_site_id = 1;
function getUserPostHandle(responseText, statusText){
	var responseJSON = responseText;
	if(typeof responseJSON.error !== "undefined"){
		$('#edituser_errbox').html("Error: "+responseJSON.error);
		$('#edituser_wait').fadeOut();
		$('#edituser_errbox').fadeIn();
	}else{
		$('#edituser_name').val(responseJSON.username);
		$('#edituser_email').val(responseJSON.email);
		$('#edituser_phone_number').val(responseJSON.phone_number);
		edit_company_id = responseJSON.company;
		edit_site_id = responseJSON.site;
		editCompaniesGet();
	}
}




/*user login*/
function　userLoginPost(){
	$('#login_wait').fadeIn();
	$('#newuser_create_success_msgbox').fadeOut();
	$('#newuser_login_failure_msgbox').fadeOut();
	var targetUrl = host+"login";
	var postInstance = [];
	postInstance.username = escape($('#login_username').val());
	postInstance.pwd = escape($('#login_password').val());
	WS.makeGenericPOSTRequest(targetUrl, WS.toParam(postInstance), userLoginPostHandle,"","");
}

function userLoginPostHandle(responseText, statusText){
	var responseJSON = responseText;
	if(typeof responseJSON.error !== "undefined"){
		$('#login_wait').fadeOut();
		$('#newuser_login_failure_msgbox').html("Error: "+responseJSON.error);
		$('#newuser_login_failure_msgbox').fadeIn();
	}else{
		$('#login_wait').fadeOut();
		persist_write(escape($('#login_password').val()),responseJSON.username,responseJSON.userid,responseJSON.jobsiteid,responseJSON.jobsitename,responseJSON.deviceid)	
		$('#inventory_form_tbody').html("");
		$('#nav_info').hide();
		$('#nav_bar').fadeIn('fast');
		$('#login_view').hide();
		$('#manage_inventory_view').show();
		$('#login_status').html("Welcome, "+responseJSON.username+" @ "+ responseJSON.jobsitename +"  <a href='' onClick='logOut()'> Logout</a>")
		searchInventoryGet();
	}
}


/*search inventory*/
function　searchInventoryGet(){
	session_c = persist_read();
	if(session_c.gocuro_username!== "" && session_c.gocuro_username!== "undefined" && session_c.gocuro_username!== "Invalid"){
		$('#item_panel_wait').fadeIn();
		$('#item_operation_success_msgbox').fadeOut();
		$('#item_operation_failure_msgbox').fadeOut();
		var targetUrl = host+"items/get_inventory?pwd="+ session_c.gocuro_password+"&username=" + session_c.gocuro_username+"&hours="+$("#item_range_select").val();
		WS.makeGenericGetRequest(targetUrl, searchInventoryGetHandle,"","");
	}else{
		window.location.reload();
	}
}
function searchInventoryGetHandle(responseText, statusText){
	$('#item_sort_ui_toggle').fadeOut();
	items_ui = [];
	items = {}; //clean up array
	var responseJSON = responseText;
	if(typeof responseJSON.error !== "undefined"){
		$('#item_panel_wait').fadeOut();
		$('#item_operation_failure_msgbox').html("Error: "+responseJSON.error);
		$('#item_operation_failure_msgbox').fadeIn();
	}else{
		var responseJSON = responseText;
		var HTMLcontent='';			
		var current_item;
		if(responseJSON.length > 0){
			
			
			for(var index = 0; index < responseJSON.length; index ++ )
			{
				items['item_'+responseJSON[index].id] = responseJSON[index];
				var HTMLdata ='<tr>';
				HTMLdata += "<td>"+responseJSON[index].id+"</td>";
				HTMLdata += "<td>"+responseJSON[index].employee_name+" ("+responseJSON[index].user_id+")</td>";
				HTMLdata += "<td>"+responseJSON[index].jobsite_name+" ("+responseJSON[index].jobsite_id+")</td>";
				HTMLdata += "<td>"+responseJSON[index].name+" ("+responseJSON[index].barcode_id+") </td>";
				HTMLdata += "<td>"+responseJSON[index].quantity+"</td>";
				HTMLdata += "<td>"+responseJSON[index].device_id+"</td>";
				HTMLdata += "<td>"+responseJSON[index].updated_at+"</td>";
				HTMLdata += "<td>"+'<button class="btn btn-mini" id="edit'+responseJSON[index].id+'\" onclick="initEditInventoryView(this.id);">Edit</button> &nbsp;<button class="btn btn-mini btn-danger" id="dele'+responseJSON[index].id+'\" onclick="initDeleteInventoryView(this.id);">Delete</button>'+"</td>";	
				HTMLdata+="</tr>";	
				current_item =  new singe_item(responseJSON[index].id,responseJSON[index].employee_name,responseJSON[index].user_id,responseJSON[index].jobsite_name,responseJSON[index].jobsite_id,responseJSON[index].name,responseJSON[index].barcode_id,responseJSON[index].quantity,responseJSON[index].device_id,responseJSON[index].updated_at,HTMLdata);
				items_ui.push(current_item);				
			}
			sort_items_ui(i_id);
			
			
		}else{
			$('#inventory_form_tbody').html("</br><h1> No inventory found </h1>");
		}
		$('#item_panel_wait').fadeOut();
		$('#item_sort_ui_toggle').fadeIn();
	}
}

							
function i_id(a,b){return b.item_id - a.item_id;}
function e_id(a,b){return b.user_id - a.user_id;}
function j_id(a,b){return b.jobsite_id - a.jobsite_id;}
function d_id(a,b){return b.device_id - a.device_id;}
function sort_items_ui(sort_func_name){
	items_ui.sort(eval(sort_func_name));
	var HTMLcontent='';		
	for(var index = 0; index < items_ui.length; index ++ )
	{
		HTMLcontent += items_ui[index].html_data	
	}
	$('#inventory_form_tbody').html(HTMLcontent);
}

/*export to CSV*/
function exportCSV(){
	session_c = persist_read();
	if(session_c.gocuro_username!== "" && session_c.gocuro_username!== "undefined" && session_c.gocuro_username!== "Invalid"){
		$('#exportcsv_wait').fadeIn();
		$('#exportcsv_msgbox').fadeOut();
		$('#exportcsv_errbox').fadeOut();
		var targetUrl = host+"csv/export_url?pwd="+ session_c.gocuro_password+"&username=" + session_c.gocuro_username;
		WS.makeGenericGetRequest(targetUrl, exportCSVHandle,"","");
	}else{
		window.location.reload();
	}
}
function exportCSVHandle(responseText, statusText){
	session_c = persist_read();
	items = {}; //clean up array
	var responseJSON = responseText;
	if(typeof responseJSON.error !== "undefined"){
		$('#exportcsv_wait').fadeOut();
		$('#exportcsv_msgbox').html("Error: "+responseJSON.error);
		$('#exportcsv_msgbox').fadeIn();
	}else{
		$('#exportfileurl').html('<br/><a href="'+responseJSON.url+"/?pwd="+ session_c.gocuro_password+"&username=" + session_c.gocuro_username+'">'+responseJSON.url+'</a>');
		$('#exportcsv_msgbox').html("Use the URL above to download file");
		$('#exportcsv_msgbox').fadeIn();
		$('#exportcsv_wait').fadeOut();
	}
}

/*new inventory*/
function　newItemPost(){
	session_c = persist_read();
	if(session_c.gocuro_username!== "" && session_c.gocuro_username!== "undefined" && session_c.gocuro_username!== "Invalid"){
		$('#newitem_wait').fadeOut();
		$('#newitem_errbox').fadeOut();
		$('#item_operation_success_msgbox').fadeOut();
		$('#item_operation_failure_msgbox').fadeOut();
		var targetUrl = host+"items";
		var postInstance = [];
		postInstance.name = escape($('#newitem_name').val());
		postInstance.quantity = escape($('#newitem_quantity').val());
		postInstance.barcode = escape($('#newitem_barcode').val());
		postInstance.username = session_c.gocuro_username;
		postInstance.pwd = session_c.gocuro_password;
		postInstance.user_id = session_c.gocuro_user_id;
		postInstance.jobsite = session_c.gocuro_jobsite_id;
		postInstance.device_id = session_c.gocuro_device_id;
		WS.makeGenericPOSTRequest(targetUrl, WS.toParam(postInstance), newItemPostHandle,"","");
	}else{
		window.location.reload();
	}
}
function newItemPostHandle(responseText, statusText){
	var responseJSON = responseText;
	if(typeof responseJSON.error !== "undefined"){
		$('#newitem_wait').fadeOut();
		$('#newitem_errbox').html("Error: "+responseJSON.error);
		$('#newitem_errbox').fadeIn();
	}else{		
		$('#newitem_wait').fadeOut();
		$('#newInventory').modal('hide');
		$('#item_operation_success_msgbox').html('Item successfully added');
		$('#item_operation_success_msgbox').fadeIn();
		searchInventoryGet();
	}
}


/*edit inventory*/
function　editItemPost(){
	session_c = persist_read();
	if(session_c.gocuro_username!== "" && session_c.gocuro_username!== "undefined" && session_c.gocuro_username!== "Invalid"){
		$('#edititem_wait').fadeOut();
		$('#edititem_errbox').fadeOut();
		$('#item_operation_success_msgbox').fadeOut();
		$('#item_operation_failure_msgbox').fadeOut();
		var targetUrl = host+"items/update";
		var postInstance = [];
		postInstance.name = escape($('#edititem_name').val());
		postInstance.quantity = escape($('#edititem_quantity').val());
		postInstance.barcode = escape($('#edititem_barcode').val());
		postInstance.item_id= target_item_id;
		postInstance.username = session_c.gocuro_username;
		postInstance.pwd = session_c.gocuro_password;
		postInstance.user_id = session_c.gocuro_user_id;
		postInstance.jobsite = session_c.gocuro_jobsite_id;
	WS.makeGenericPOSTRequest(targetUrl, WS.toParam(postInstance), editItemPostHandle,"","");
	}else{
		window.location.reload();
	}
	
}
function editItemPostHandle(responseText, statusText){
	var responseJSON = responseText;
	if(typeof responseJSON.error !== "undefined"){
		$('#edititem_wait').fadeOut();
		$('#edititem_errbox').html("Error: "+responseJSON.error);
		$('#edititem_errbox').fadeIn();
	}else{
		$('#edititem_wait').fadeOut();
		$('#editInventory').modal('hide');
		$('#item_operation_success_msgbox').html('Item successfully edited');
		$('#item_operation_success_msgbox').fadeIn();
		searchInventoryGet();
	}
}


/*delete inventory*/
function　deleteItemPost(){
	session_c = persist_read();
	if(session_c.gocuro_username!== "" && session_c.gocuro_username!== "undefined" && session_c.gocuro_username!== "Invalid"){
		$('#deleteitem_wait').fadeOut();
		$('#deleteitem_errbox').fadeOut();
		$('#item_operation_success_msgbox').fadeOut();
		$('#item_operation_failure_msgbox').fadeOut();
		var targetUrl = host+"items/destroy/"+target_item_id;
		var postInstance = [];
		postInstance.username = session_c.gocuro_username;
		postInstance.pwd = session_c.gocuro_password;
		postInstance.user_id = session_c.gocuro_user_id;
		postInstance.jobsite = session_c.gocuro_jobsite_id;
	WS.makeGenericPOSTRequest(targetUrl, WS.toParam(postInstance), deleteItemPostHandle,"","");
	}else{
		window.location.reload();
	}
	
}
function deleteItemPostHandle(responseText, statusText){
	var responseJSON = responseText;
	if(typeof responseJSON.error !== "undefined"){
		$('#deleteitem_wait').fadeOut();
		$('#deleteitem_errbox').html("Error: "+responseJSON.error);
		$('#deleteitem_errbox').fadeIn();
	}else{
		$('#deleteitem_wait').fadeOut();
		$('#deleteInventory').modal('hide');
		$('#item_operation_success_msgbox').html('Item successfully deleted');
		$('#item_operation_success_msgbox').fadeIn();
		searchInventoryGet();
	}
}








